package com.shsc.example.project;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AddressActivity extends AppCompatActivity implements View.OnClickListener {

    public static final int REQUEST_READ_CONTACTS_PERMISSION = 0x0001;
    public static final int REQUEST_WRITE_CONTACTS_PERMISSION = 0x0002;
    List contactsList = new ArrayList();
    private RecyclerView mRvContactsView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address);


        mRvContactsView = (RecyclerView) findViewById(R.id.rv_contacts);

        Button btQueryContacts = (Button) findViewById(R.id.bt_query_contacts);
        Button btAddContacts = (Button) findViewById(R.id.bt_add_contacts);
        btQueryContacts.setOnClickListener(this);
        btAddContacts.setOnClickListener(this);
    }


    /**
     * 读取本地通讯录
     */
    private void readContacts() {
        // 检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_READ_CONTACTS_PERMISSION);
        } else {
            queryContacts();
        }
    }

    private void addContact() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CONTACTS}, REQUEST_WRITE_CONTACTS_PERMISSION);
        } else {
            saveContacts();
        }
    }


    /**
     * 权限获取同意后 回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_READ_CONTACTS_PERMISSION:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    queryContacts();
                } else {
                    Toast.makeText(this, "由于你拒绝了此权限，所以导致获取联系人失败", Toast.LENGTH_SHORT).show();
                }
                break;
            case REQUEST_WRITE_CONTACTS_PERMISSION:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    saveContacts();
                } else {
                    Toast.makeText(this, "由于你拒绝了此权限，所以导致写入联系人失败", Toast.LENGTH_SHORT).show();
                }
        }
    }

    /**
     * 写入联系人
     */
    private void saveContacts() {
        Cursor cursor = null;
        try {
            ContentResolver cr = this.getContentResolver();
            ContentValues contacts = new ContentValues();
            contacts.put("name", "zhao");
            contacts.put("phone", "911");
            cr.insert(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, contacts
            );
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cursor.close();
        }
    }

    /**
     * 读取手机的联系人信息
     */
    private void queryContacts() {
        Cursor cursor = null;
        try {
            ContentResolver cr = this.getContentResolver();
            cursor = cr.query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    null,
                    null,
                    null
            );
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    // 获取联系人姓名
                    String userName =
                            cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    // 获取联系人手机号
                    String userPhone =
                            cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    HashMap<String, String> map = new HashMap();
                    map.put("name", userName);
                    map.put("phone", userPhone);
                    contactsList.add(map);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cursor.close();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_query_contacts:
                // 读取通讯录
                readContacts();
                // 刷新布局
                setContactsList();
                break;
            case R.id.bt_add_contacts:
                addContact();
                break;
        }
    }

    /**
     * 渲染列表布局
     */
    private void setContactsList() {
        ContactsAdapter adapter = new ContactsAdapter();
        adapter.setDatas(contactsList);
        mRvContactsView.setAdapter(adapter);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        mRvContactsView.setLayoutManager(linearLayoutManager);
    }
}
